package com.shared.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.shared.util.JwtUtils;
import org.joda.time.DateTime;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import org.springframework.stereotype.Component;
import org.springframework.util.StreamUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Component
public class LoginJwtFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return FilterConstants.POST_TYPE;
    }

    @Override
    public int filterOrder() {
        return FilterConstants.SEND_RESPONSE_FILTER_ORDER - 1;
    }

    @Override
    public boolean shouldFilter() {
        RequestContext context = RequestContext.getCurrentContext();
        HttpServletRequest request = context.getRequest();
        String uri = request.getRequestURI();
        if (uri.endsWith("/login")) {
            return true;
        }
        return false;
    }

    @Override
    public Object run() throws ZuulException {
        //生成一个token，将token 响应给客户端浏览器：添加到响应头中
        RequestContext context = RequestContext.getCurrentContext();
        //获取响应数据流对象
        InputStream inputStream = context.getResponseDataStream();
        try {
            String responseBody = StreamUtils.copyToString(inputStream, StandardCharsets.UTF_8);
            System.out.println("--->" + responseBody);
            ObjectMapper mapper = new ObjectMapper();
            //controller中的返回结果
            Map res = mapper.readValue(responseBody, Map.class);
            String mobile = (String) res.get("data");
            Map claims = new HashMap();
            claims.put("mobile", mobile);
            Date expireDate = DateTime.now().plusDays(2).toDate();
            //生成token
            String token = JwtUtils.createToken(expireDate, claims);
            context.getResponse().addHeader("Access-Control-Expose-Headers", "token");
            context.getResponse().addHeader("token", token);
            context.setSendZuulResponse(true);
            //将响应体中数据，写到响应（response）中
            context.setResponseBody(responseBody);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}
